<?php
namespace Modules\User\Controllers;

class TeamController extends \Phalcon\Mvc\Controller {
	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function indexAction($id) {
		$service = $this -> user::getServiceInstance() -> find([
			'columns' => 'user_id, account',
			'conditions' => 'pid = ' . $id,
			'order' => 'user_id DESC'
		]);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>'无下级用户']);
		}

		$thisWeekTime = time() - 604800;

		$models = [];
    foreach($service['user'] as $k => $v) {
			$models[$k] = $v -> toArray();
			$resTeam = $this -> user::getTeamServiceInstance() -> findFirst([
				'conditions' => 'user_id = ' . $v -> user_id,
			]);

			$models[$k]['team_total'] = 0;
			$models[$k]['this_week_trade_buy_total'] = 0;
			if($resTeam['code'] != 0) {
				$thisWeekBuy = $this -> trade::getBuyServiceInstance() -> find([
					'conditions' => 'status = 6 AND from_user_id = ' . $v -> user_id . ' AND create_time >= ' . $thisWeekTime,
					'columns' => 'original_amount'
				]);
				if($thisWeekBuy['code'] == 0) {
					foreach($thisWeekBuy['trade_buy'] as $buy) {
						$models[$k]['this_week_trade_buy_total'] += $buy -> original_amount;
					}
				}
			} else {
				foreach($resTeam['model'] -> data as $tv) {
					$userIds = '';
					foreach($tv as $id => $v) {
						$userIds .= $id . ',';
					}
					$userIds = rtrim($userIds, ',');
					
					if(!empty($userIds)) {
						$thisWeekBuy = $this -> trade::getBuyServiceInstance() -> find([
							'conditions' => 'status = 6 AND from_user_id in (' . $userIds . ') AND create_time >= ' . $thisWeekTime,
							'columns' => 'original_amount'
						]);
						if($thisWeekBuy['code'] == 0) {
							foreach($thisWeekBuy['trade_buy'] as $buy) {
								$models[$k]['this_week_trade_buy_total'] += $buy -> original_amount;
							}
						}
					}

					$models[$k]['team_total'] += count($tv);
				}
			}
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'models' => $models]);
	}
}